package fr.curriculumvitae.anthony.stephan;

import java.io.File;
import java.util.LinkedList;

import com.parse.ParseAnalytics;

import fr.curriculumvitae.anthony.stephan.R;
import fr.curriculumvitae.anthony.stephan.activities.AboutActivity;
import fr.curriculumvitae.anthony.stephan.activities.AdminDashboardActivity;
import fr.curriculumvitae.anthony.stephan.activities.PwdPickerActivity;
import fr.curriculumvitae.anthony.stephan.backend.BackEnd;
import fr.curriculumvitae.anthony.stephan.backend.IGetMessagesCallback;
import fr.curriculumvitae.anthony.stephan.backend.IGetPdfCVCallback;
import fr.curriculumvitae.anthony.stephan.fragments.CenterOfInterestsFragment;
import fr.curriculumvitae.anthony.stephan.fragments.ContactFragment;
import fr.curriculumvitae.anthony.stephan.fragments.ExperiencesFragment;
import fr.curriculumvitae.anthony.stephan.fragments.ProductionsFragment;
import fr.curriculumvitae.anthony.stephan.fragments.SkillsFragment;
import fr.curriculumvitae.anthony.stephan.fragments.TrainingsFragment;
import fr.curriculumvitae.anthony.stephan.fragments.WhoAmIFragment;
import fr.curriculumvitae.anthony.stephan.objects.Message;
import fr.curriculumvitae.anthony.stephan.swipeytabs.SwipeyTabs;
import fr.curriculumvitae.anthony.stephan.swipeytabs.SwipeyTabsAdapter;
import fr.curriculumvitae.anthony.stephan.utils.StateManager;
import fr.curriculumvitae.anthony.stephan.utils.UpdateChecker;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class SwipeyTabsActivity extends FragmentActivity {
	
	private static final int REQUEST_PASSWORD = 1004;
	
	public static final String PACKAGE_NAME = "fr.curriculumvitae.anthony.stephan";
	private static final String PRIVATE_PREFS = "fr.curriculumvitae.anthony.stephan";
	private static final String PREF_ADMIN_MENU = PRIVATE_PREFS+".AdminMenu";
	
	public static final int SWIPEY_TAB_WHO_AM_I 			= 0;
	public static final int SWIPEY_TAB_TRAININGS 			= 1;
	public static final int SWIPEY_TAB_EXPERIENCES 			= 2;
	public static final int SWIPEY_TAB_SKILLS 				= 3;
	public static final int SWIPEY_TAB_PRODUCTIONS 			= 4;
	public static final int SWIPEY_TAB_CENTER_OF_INTERESTS 	= 5;
	public static final int SWIPEY_TAB_CONTACT 				= 6;

	public static Context context;
	public static AlertDialog mDialog;
	public static Toast mToast;
	
	private static String [] titles = {};
	private static boolean adminUnlocked = false;
	
	private SwipeyTabs mTabs;
	private ViewPager mViewPager;
	private SwipeyTabsPagerAdapter mAdapter;
	
	private boolean parseInitialized;
	
	
	  ///////////////
	 // LIFECYCLE //
	///////////////
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		
		// check for update
		new UpdateChecker(this, PACKAGE_NAME, false, true, false, false).execute();
		
		setContentView(R.layout.activity_swipeytab);
		
		// initialize backend
		if(!parseInitialized) {
			ParseAnalytics.trackAppOpened(getIntent());
			parseInitialized = true;
		}
		new DoAsyncNetworkTask().execute();
		
		// fetch and init views
		fetchViews();
		initAdminMenu();
		titles = getResources().getStringArray(R.array.swipey_tabs_labels);
		
		// init adapter
		mAdapter = new SwipeyTabsPagerAdapter(this, getSupportFragmentManager());
		mViewPager.setAdapter(mAdapter);
		mTabs.setAdapter(mAdapter);
		mViewPager.setOnPageChangeListener(mTabs);
		mViewPager.setCurrentItem(0);
		
		// init utils
		mDialog = new ProgressDialog(this);
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if(mDialog != null) {
			mDialog.dismiss();
		}
	}
	
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {  
    	super.onActivityResult(requestCode, resultCode, data);
    	if(requestCode == REQUEST_PASSWORD) {
			if(mToast!=null){
				mToast.cancel();
			}
    		if(resultCode == Activity.RESULT_OK) {
    			mToast = Toast.makeText(this, getResources().getString(R.string.pwd_picker_success), Toast.LENGTH_LONG);
    			mToast.show();
    			if(mDialog != null && mDialog.isShowing()) {
    				mDialog.setTitle(getResources().getString(R.string.admin_get_messages_dialog_title));
    				mDialog.setMessage(getResources().getString(R.string.admin_get_messages_dialog_message));
    			} else {
        			mDialog = ProgressDialog.show(this, 
							getResources().getString(R.string.admin_get_messages_dialog_title), 
							getResources().getString(R.string.admin_get_messages_dialog_message));
    			}
    			BackEnd.getMessages(getMessagesCallback);
    		} else if(resultCode == Activity.RESULT_FIRST_USER) {
    			mToast = Toast.makeText(this, getResources().getString(R.string.pwd_picker_failed), Toast.LENGTH_LONG);
    			mToast.show();
    		}
    	}
    }
	
	private void fetchViews() {
		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
	}
	
	public static void enableAdminMenu() {
		adminUnlocked = true;
		SharedPreferences prefs = context.getSharedPreferences(PRIVATE_PREFS, Context.MODE_PRIVATE);
		Editor editor = prefs.edit();
		editor.putBoolean(PREF_ADMIN_MENU, adminUnlocked);
		editor.commit();
	}
	
	private static void initAdminMenu() {
		SharedPreferences prefs = context.getSharedPreferences(PRIVATE_PREFS, Context.MODE_PRIVATE);
		adminUnlocked = prefs.getBoolean(PREF_ADMIN_MENU, false);
	}
	
	public void swipeToTab(int tabID) {
		mViewPager.setCurrentItem(tabID, true);
	}
	
	
	  //////////
	 // MENU //
	//////////
	
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.getItem(2).setEnabled(adminUnlocked);
		return true;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.menu_pdf:
	        	downloadPdfCV();
	            return true;
	        case R.id.menu_about:
	        	Intent i = new Intent(SwipeyTabsActivity.this, AboutActivity.class);
	        	startActivity(i);
	        	return true;
	        case R.id.menu_admin:
				Intent pwd = new Intent(this, PwdPickerActivity.class);
				pwd.putExtra(PwdPickerActivity.EXTRA_DISMISS_DIALOG, false);
				startActivityForResult(pwd, REQUEST_PASSWORD);
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	public void downloadPdfCV() {
		mDialog = ProgressDialog.show(context, 
						getString(R.string.dialog_download_cv_title), 
						getString(R.string.dialog_download_cv_message));
		mDialog.setCancelable(false);
    	BackEnd.getPdfCV(new IGetPdfCVCallback() {
			@Override
			public void getPdfCVEnded(boolean success, File file, String message) {
				mDialog.dismiss();
				if(success && file != null) {
					mDialog = new AlertDialog.Builder(context)
									.setTitle(getString(R.string.dialog_download_cv_ended_title))
									.setMessage(getString(R.string.dialog_download_cv_ended_message))
									.setNegativeButton(
											getString(android.R.string.no), 
											null)
									.setPositiveButton(android.R.string.yes, 
											new OnOpenPdfCVClickListener(file))
									.create();
				} else {
					mDialog = new AlertDialog.Builder(context)
					.setTitle(getString(R.string.dialog_download_cv_failed_title))
					.setMessage(getString(R.string.dialog_download_cv_failed_message))
					.create();
				}
				mDialog.show();
			}
    	});
	}
	
	
	  ///////////////
	 // LISTENERS //
	///////////////
	
	private class OnOpenPdfCVClickListener implements Dialog.OnClickListener {
		private File file;
		public OnOpenPdfCVClickListener(File file) {
			this.file = file;
		}
		@Override
		public void onClick(DialogInterface dialog, int which) {
			Intent intent = new Intent();
			intent.setAction(android.content.Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(file), "application/pdf");
			startActivity(intent); 
		}
	};
	
	private IGetMessagesCallback getMessagesCallback = new IGetMessagesCallback() {
		@Override
		public void getMessagesEnded(boolean success, LinkedList<Message> messages, String message) {
			if(mDialog != null) {
				mDialog.dismiss();
			}
			if(message == null && messages != null) {
				Intent intent = new Intent(context, AdminDashboardActivity.class);
				intent.putExtra("messages", messages);
				startActivity(intent);
			} else {
				if(mToast!=null) {
					mToast.cancel();
				}
				mToast = Toast.makeText(context, getResources().getString(R.string.admin_get_messages_dialog_error), Toast.LENGTH_LONG);
				mToast.show();
			}
		}
	};
	
	  ///////////////////
	 // INNER ADAPTER //
	///////////////////
	
	private class SwipeyTabsPagerAdapter extends FragmentPagerAdapter implements SwipeyTabsAdapter {
		
		private final Context mContext;
		
		public SwipeyTabsPagerAdapter(Context context, FragmentManager fm) {
			super(fm);
			this.mContext = context;
		}

		@Override
		public Fragment getItem(int position) {
			Fragment toDisplay = null;
			switch(position) {
				case SWIPEY_TAB_WHO_AM_I:
					toDisplay = WhoAmIFragment.getInstance();
					break;
				case SWIPEY_TAB_TRAININGS:
					toDisplay = TrainingsFragment.getInstance();
					break;
				case SWIPEY_TAB_EXPERIENCES:
					toDisplay = ExperiencesFragment.getInstance();
					break;
				case SWIPEY_TAB_SKILLS:
					toDisplay = SkillsFragment.getInstance();
					break;
				case SWIPEY_TAB_PRODUCTIONS:
					toDisplay = ProductionsFragment.getInstance();
					break;
				case SWIPEY_TAB_CENTER_OF_INTERESTS:
					toDisplay = CenterOfInterestsFragment.getInstance();
					break;
				case SWIPEY_TAB_CONTACT:
					toDisplay = ContactFragment.getInstance();
					break;
			}
			return toDisplay;
		}
		
		@Override
		public int getCount() {
			return titles.length;
		}
		
		@Override
		public TextView getTab(final int position, SwipeyTabs root) {
			TextView view = (TextView) LayoutInflater.from(mContext).inflate(R.layout.swipey_tab_indicator, root, false);
			view.setText(titles[position]);
			view.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					mViewPager.setCurrentItem(position);
				}
			});
			return view;
		}
	}
	
	
	  ////////////////
	 // ASYNC TASK //
	////////////////
	
    private class DoAsyncNetworkTask extends AsyncTask<Void, Void, Void> {
        protected Void doInBackground(Void... args) {
                    if(parseInitialized) {
                            StateManager.fetchState();
                    }
                    return null;
        }
    }

}
